"use client"
import CreateModal from "./components/CreateModal"
import UpdateModal from "./components/UpdateModal"
import UpdateBankModal from "./components/UpdateBankModal"
import BatchAddQuestionsToBankModal from "./components/BatchAddQuestionsToBankModal"
import BatchRemoveQuestionsFromBankModal from "./components/BatchRemoveQuestionsFromBankModal"
import { listQuestionByPage, deleteQuestion, batchDeleteQuestions } from "@/api/question"
import { PlusOutlined } from "@ant-design/icons"
import { PageContainer, ProTable } from "@ant-design/pro-components"
import { Button, message, Popconfirm, Space, Table, Typography } from "antd"
import React, { useRef, useState } from "react"
import TagList from "@/components/tag-list"
import MdEditor from "@/components/md-editor"
import type { ActionType, ProColumns } from "@ant-design/pro-components"

/**
 * 题目管理页面
 */
const QuestionAdminPage: React.FC = () => {
  // 是否显示新建窗口
  const [createModalVisible, setCreateModalVisible] = useState<boolean>(false)
  // 是否显示更新窗口
  const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false)
  // 是否显示更新所属题库窗口
  const [updateBankModalVisible, setUpdateBankModalVisible] = useState<boolean>(false)
  // 是否显示批量向题库添加题目弹窗
  const [batchAddQuestionsToBankModalVisible, setBatchAddQuestionsToBankModalVisible] = useState<boolean>(false)
  // 是否显示批量从题库移除题目弹窗
  const [batchRemoveQuestionsToBankModalVisible, setBatchRemoveQuestionsToBankModalVisible] = useState<boolean>(false)
  // 选择的题目 id 列表
  const [selectedQuestionIdList, setSelectedQuestionIdList] = useState<number[]>([])
  const actionRef = useRef<ActionType>()
  // 当前用户点击的数据
  const [currentRow, setCurrentRow] = useState<Question>()

  /**
   * 删除节点
   *
   * @param row
   */
  const handleDelete = async (row: Question) => {
    const hide = message.loading("正在删除")
    try {
      await deleteQuestion({
        id: row.id
      })
      hide()
      message.success("删除成功")
      actionRef?.current?.reload()
    } catch (error) {
      hide()
      error instanceof Error && message.error("删除失败，" + error.message)
    }
  }

  /**
   * 批量删除题目
   *
   * @param questionIdList
   */
  const handleBatchDeleteQuestions = async (questionIdList: number[]) => {
    const hide = message.loading("正在操作")
    try {
      await batchDeleteQuestions(questionIdList)
      hide()
      message.success("操作成功")
      actionRef?.current?.reload()
    } catch (error) {
      hide()
      error instanceof Error && message.error("操作失败，" + error.message)
    }
  }

  /**
   * 表格列配置
   */
  const columns: ProColumns<Question>[] = [
    {
      title: "id",
      dataIndex: "id",
      valueType: "text",
      hideInForm: true
    },
    {
      title: "所属题库",
      dataIndex: "questionBankId",
      valueType: "text",
      hideInForm: true,
      hideInTable: true
    },
    {
      title: "标题",
      dataIndex: "title",
      valueType: "text"
    },
    {
      title: "内容",
      dataIndex: "content",
      valueType: "text",
      hideInSearch: true,
      width: 240,
      // @ts-expect-error fieldProps是存在的
      renderFormItem: (_, { fieldProps }) => {
        // value 和 onchange 会通过 form 自动注入
        return <MdEditor {...fieldProps} />
      }
    },
    {
      title: "答案",
      dataIndex: "answer",
      valueType: "text",
      hideInSearch: true,
      width: 640,
      // @ts-expect-error fieldProps是存在的
      renderFormItem: (_, { fieldProps }) => {
        // value 和 onchange 会通过 form 自动注入
        return <MdEditor {...fieldProps} />
      }
    },
    {
      title: "标签",
      dataIndex: "tags",
      valueType: "select",
      fieldProps: {
        mode: "tags"
      },
      render: (_, record) => {
        const tags = JSON.parse(record.tags || "[]")
        return <TagList tags={tags} />
      }
    },
    {
      title: "创建用户",
      dataIndex: "userId",
      valueType: "text",
      hideInForm: true
    },

    {
      title: "创建时间",
      sorter: true,
      dataIndex: "createTime",
      valueType: "dateTime",
      hideInSearch: true,
      hideInForm: true
    },
    {
      title: "编辑时间",
      sorter: true,
      dataIndex: "editTime",
      valueType: "dateTime",
      hideInSearch: true,
      hideInForm: true
    },
    {
      title: "更新时间",
      sorter: true,
      dataIndex: "updateTime",
      valueType: "dateTime",
      hideInSearch: true,
      hideInForm: true
    },
    {
      title: "操作",
      dataIndex: "option",
      valueType: "option",
      render: (_, record) => (
        <Space size="middle">
          <Typography.Link
            onClick={() => {
              setCurrentRow(record)
              setUpdateModalVisible(true)
            }}
          >
            修改
          </Typography.Link>
          <Typography.Link
            onClick={() => {
              setCurrentRow(record)
              setUpdateBankModalVisible(true)
            }}
          >
            修改所属题库
          </Typography.Link>
          <Typography.Link type="danger" onClick={() => handleDelete(record)}>
            删除
          </Typography.Link>
        </Space>
      )
    }
  ]

  return (
    <PageContainer>
      <ProTable<Question>
        headerTitle={"查询表格"}
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120
        }}
        scroll={{
          x: true
        }}
        rowSelection={{
          selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT]
        }}
        tableAlertRender={({ selectedRowKeys, onCleanSelected }) => {
          return (
            <Space size={24}>
              <span>
                已选 {selectedRowKeys.length} 项
                <a style={{ marginInlineStart: 8 }} onClick={onCleanSelected}>
                  取消选择
                </a>
              </span>
            </Space>
          )
        }}
        tableAlertOptionRender={({ selectedRowKeys }) => {
          return (
            <Space size={16}>
              <Button
                onClick={() => {
                  // 打开弹窗
                  setSelectedQuestionIdList(selectedRowKeys as number[])
                  setBatchAddQuestionsToBankModalVisible(true)
                }}
              >
                批量向题库添加题目
              </Button>
              <Button
                onClick={() => {
                  // 打开弹窗
                  setSelectedQuestionIdList(selectedRowKeys as number[])
                  setBatchRemoveQuestionsToBankModalVisible(true)
                }}
              >
                批量从题库移除题目
              </Button>
              <Popconfirm
                title="确认删除"
                description="你确定要删除这些题目么？"
                onConfirm={() => {
                  // 批量删除题目
                  handleBatchDeleteQuestions(selectedRowKeys as number[])
                }}
                okText="确定"
                cancelText="取消"
              >
                <Button danger>批量删除题目</Button>
              </Popconfirm>
            </Space>
          )
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setCreateModalVisible(true)
            }}
          >
            <PlusOutlined /> 新建
          </Button>
        ]}
        request={async (params, sort, filter) => {
          const sortField = Object.keys(sort)?.[0]
          const sortOrder = sort?.[sortField] ?? undefined

          const { data, code } = await listQuestionByPage({
            ...params,
            sortField,
            sortOrder,
            ...filter
          })

          return {
            success: code === 0,
            data: data?.records || [],
            total: Number(data?.total) || 0
          }
        }}
        columns={columns}
      />
      <CreateModal
        visible={createModalVisible}
        columns={columns}
        onSubmit={() => {
          setCreateModalVisible(false)
          actionRef.current?.reload()
        }}
        onCancel={() => {
          setCreateModalVisible(false)
        }}
      />
      <UpdateModal
        visible={updateModalVisible}
        columns={columns}
        oldData={currentRow}
        onSubmit={() => {
          setUpdateModalVisible(false)
          setCurrentRow(undefined)
          actionRef.current?.reload()
        }}
        onCancel={() => {
          setUpdateModalVisible(false)
        }}
      />
      <UpdateBankModal
        questionId={currentRow?.id}
        visible={updateBankModalVisible}
        onCancel={() => {
          setUpdateBankModalVisible(false)
        }}
      />
      <BatchAddQuestionsToBankModal
        visible={batchAddQuestionsToBankModalVisible}
        questionIdList={selectedQuestionIdList}
        onSubmit={() => {
          setBatchAddQuestionsToBankModalVisible(false)
          setSelectedQuestionIdList([])
          actionRef.current?.reload()
        }}
        onCancel={() => setBatchAddQuestionsToBankModalVisible(false)}
      />
      <BatchRemoveQuestionsFromBankModal
        visible={batchRemoveQuestionsToBankModalVisible}
        questionIdList={selectedQuestionIdList}
        onSubmit={() => {
          setBatchRemoveQuestionsToBankModalVisible(false)
          setSelectedQuestionIdList([])
          actionRef.current?.reload()
        }}
        onCancel={() => setBatchRemoveQuestionsToBankModalVisible(false)}
      />
    </PageContainer>
  )
}
export default QuestionAdminPage
